package com.ruoyi.ybUpload.service.upload.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.ybUpload.domain.MainForm;
import com.ruoyi.ybUpload.domain.QueryParams;
import com.ruoyi.ybUpload.service.upload.YBUploadBusinessService;
import com.ruoyi.ybUpload.service.upload.YBUploadInterfaceService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class YBUploadBusinessServiceImpl implements YBUploadBusinessService {

    @Autowired
    private YBUploadInterfaceService ybUploadInterfaceService;

    private static final String url = "http://10.98.34.102/mbs-hiIntf-hechi/web/api/fsi/callService";

    public void saveRecord(List<MainForm> list){
        //list.get(0).get
        for (MainForm e:list) {

        }
    }

    /**
     * 库存盘存
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadStocktaking(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3501接口初始化库存
        MainForm mainForm3501 = ybUploadInterfaceService.structure3501(queryParams);
        //调用3502接口进行入库操作（有追溯码）
        MainForm mainForm3502 = ybUploadInterfaceService.structure3502(queryParams, "108");
        //插入业务变更
        list.add(mainForm3501);
        list.add(mainForm3502);
        return list;
    }

    /**
     * 采购/入库
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadEntryStock(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3503接口上传商品基本信息（无追溯码）
        MainForm mainForm3503 = ybUploadInterfaceService.structure3503(queryParams);
        test1(JSON.toJSONString(mainForm3503));
        //调用3502接口进行入库操作（有追溯码）
        MainForm mainForm3502 = ybUploadInterfaceService.structure3502(queryParams, "108");
        list.add(mainForm3503);
        list.add(mainForm3502);
        return list;
    }

    /**
     * 出库
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadOutStock(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3502接口进行出库操作
        MainForm mainForm3502 = ybUploadInterfaceService.structure3502(queryParams, "102");
        list.add(mainForm3502);
        return list;
    }

    /**
     * 3505:销售
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadSell(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3505
        MainForm mainForm3505 = ybUploadInterfaceService.structure3505(queryParams);
        list.add(mainForm3505);
        return list;
    }




    /**
     * 耗材入出库
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadConsumables(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3503接口上传商品基本信息（无追溯码）
        MainForm mainForm3503 = ybUploadInterfaceService.structure3503(queryParams);
        //调用3502接口进行入库操作（有追溯码）
        MainForm mainForm3502in = ybUploadInterfaceService.structure3502(queryParams, "108");
        //调用3502接口进行出库操作（有追溯码）
        MainForm mainForm3502out = ybUploadInterfaceService.structure3502(queryParams, "102");
        //调用3505接口进行销售操作（有追溯码）
        MainForm mainForm3505 = ybUploadInterfaceService.structure3505(queryParams);

        list.add(mainForm3503);
        list.add(mainForm3502in);
        list.add(mainForm3502out);
        list.add(mainForm3505);
        return list;
    }

    /**
     * 3508:查询3501盘存信息
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadSelect3501(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3508接口查询3501
        MainForm mainForm3501 = ybUploadInterfaceService.structure3508(queryParams);
        list.add(mainForm3501);
        //String result = test1(JSON.toJSONString(mainForm3501));
        return list;
    }

    /**
     * 3509:查询3502变更记录
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadSelect3502(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用接口3509查询3502商品库存信息
        MainForm mainForm3509 = ybUploadInterfaceService.structure3509(queryParams);
        list.add(mainForm3509);
        return list;
    }

    /**
     * 3510:查询3503采购信息
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadSelect3503(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用接口3510查询3503商品采购信息
        MainForm mainForm3510 = ybUploadInterfaceService.structure3510(queryParams);
        list.add(mainForm3510);
        return list;
    }
    /**
     * 3513:查询3505采购信息
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadSelect3505(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用接口3513查询3505商品采购信息
        MainForm mainForm3513 = ybUploadInterfaceService.structure3513(queryParams);
        list.add(mainForm3513);
        return list;
    }

    /**
     * 3504:采购退货
     * @param queryParams
     * @return
     */
    @Override
    public List<MainForm> uploadSelect3504(QueryParams queryParams) {
        List<MainForm> list = new ArrayList<>();
        //调用3504
        MainForm mainForm3504 = ybUploadInterfaceService.structure3504(queryParams);
        list.add(mainForm3504);
        return list;
    }


    @Override
    public String uploadSignIn(QueryParams queryParams) {
        //调用9001接口实现登录
        MainForm signIn = ybUploadInterfaceService.structure9001(queryParams);
        String result = test1(JSON.toJSONString(signIn));

        JSONObject jsonFromResult = JSON.parseObject(result);

        Object output = jsonFromResult.get("output");
        JSONObject jsonFromOutput = JSON.parseObject(output.toString());

        Object signinoutb = jsonFromOutput.get("signinoutb");
        JSONObject jsonFromSigninoutb = JSON.parseObject(signinoutb.toString());

        Object sign_no = jsonFromSigninoutb.get("sign_no");
        System.out.println("sign_no:"+sign_no.toString());
        //修改mainform的signin字段
        return result;
    }

    public String test1(String json) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
        httppost.setConfig(requestConfig);
        ByteArrayEntity entity = new ByteArrayEntity(json.getBytes(StandardCharsets.UTF_8));
        entity.setContentType("text/plain");
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                httppost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity responseEntity = response.getEntity();
            String result;
            if (responseEntity != null) {
                //返回字符串
                result = EntityUtils.toString(responseEntity, "UTF-8");
                return  result;
            }
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            throw new RuntimeException("提交给服务器的请求，不符合HTTP协议", e);
        } catch (IOException e) {
            throw new RuntimeException("向服务器承保接口发起http请求,执行post请求异常", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
